﻿using Sustainalytics.Entities;
using System.Linq;
using System.Linq.Dynamic;
using MongoDB.Driver;
using MongoDB.Driver.Linq;

namespace Sustainalytics.DataLayer
{
    public static class CompanyScreeningExtensions
    {
        public static IQueryable<ResultOutput> Filter(this IQueryable<ResultOutput> query, ResultOutputFilter filter)
        {
            if (filter.FilterId.HasValue)
            {
                query = query.Where(el => el.FilterId == filter.FilterId.Value);
            }

            if (filter.IsValid.HasValue)
            {
                query = query.Where(el => el.IsValid == filter.IsValid.Value);
            }

            return query;
        }

        public static IQueryable<ResultOutput> Order(this IQueryable<ResultOutput> query, string orderBy, bool asc = true)
        {
            if (string.IsNullOrEmpty(orderBy))
            {
                return query;
            }

            query = query.OrderBy(string.Format("{0} {1}", orderBy, asc ? "ASC" : "DESC"));

            return query;
        }


        public static IMongoCollection<T> GetCollectionByNameType<T>(this IMongoDatabase clientMongo)
        {
            return clientMongo.GetCollection<T>(typeof(T).Name);
        }

        public static IQueryable<T> GetAsQueryable<T>(this IMongoDatabase clientMongo)
        {
            return clientMongo.GetCollection<T>(typeof(T).Name).AsQueryable();
        }
    }
}
